import { createRef, useEffect } from 'react';
import { Button, Divider, Table, Modal, Space, message } from 'antd';
import MenuModal from './MenuModal';
import { observer } from 'mobx-react'
import menu from '../../mobx/menu';

function MenuIndex() {

  // 创建ref对象 
  const dialog = createRef(null);


  // 删除菜单
  const menuDel = (id) => {
    // 显示确认提示框
    Modal.confirm({
      title: '提示',
      content: '确认删除?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 删除菜单
        const res = await menu.menuRemove(id);
        if (res.code !== 200) {
          message.error(res.msg);
        }
      }
    });
  }


  // 编辑菜单
  const edit = (row) => {
    const { current } = dialog;
    // console.log(row);
    // 显示对话框组件
    current.toggle();
    // 将待编辑的菜单数据传递给对话框组件
    current.getMenuData({ ...row });
  }

  // 表格列配置
  const columns = [
    {
      title: '菜单序号',
      dataIndex: 'id'
    },
    {
      title: '菜单标题',
      dataIndex: 'title',
    },
    {
      title: '菜单地址',
      dataIndex: 'url',
    },
    {
      title: '操作',
      render: (row) => {
        if (row.id > 0) {
          return <Space>
            <Button onClick={() => edit(row)} type='primary'>编辑</Button>
            <Button type='primary' danger onClick={() => menuDel(row.id)}>删除</Button>
          </Space>
        }

      }
    }
  ];



  // 切换对话框显示状态
  const toggleModal = () => {
    const { current } = dialog;
    current.toggle();
  }

  useEffect(() => {
    // 请求菜单列表数据
    menu.getMenuList();
  }, []);


  return (
    <div className='table-container'>
      <h1>菜单管理</h1>
      <Button className='btn-add' type='primary' onClick={toggleModal}>新增</Button>
      <Divider></Divider>
      {/* defaultExpandAllRows: 展开所有行 */}
      <Table pagination={false} columns={columns}
        defaultExpandAllRows={true}
        dataSource={menu.menuList} rowKey='id'
        expandable={{ defaultExpandAllRows: false }} />
      {/* 添加/编辑对话框 */}
      <MenuModal ref={dialog} />
    </div>
  )
}

export default observer(MenuIndex);